import fs from 'node:fs'
import { ClientRequest, IncomingMessage, ServerResponse } from 'node:http'
import path from 'node:path'

const urlParamsToObj = (url: string) => {
    const params = url.split('?')[1]
    if (!params) return {}
    const paramsArr = params.split('&')
    const obj: any = {}
    paramsArr.forEach((item) => {
        const [key, value] = item.split('=')
        obj[key] = value
    })
    return obj
}

// 白板保存
const boardSave = async (
    req: IncomingMessage,
    res: ServerResponse<IncomingMessage>
) => {
    let body: any = ''
    req.on('data', (chunk) => {
        body += chunk
    })
    req.on('end', () => {
        const jsonFilePath = path.resolve('./src/pages/Board/test.json')
        fs.writeFileSync(jsonFilePath, body)
        res.setHeader('Content-Type', 'application/json')
        res.end(
            JSON.stringify({
                success: true,
            })
        )
    })
}

const isDevlopment = async (
    _req: IncomingMessage,
    res: ServerResponse<IncomingMessage>
) => {
    res.setHeader('Content-Type', 'application/json')
    console.log(111)
    res.end(
        JSON.stringify({
            success: true,
            data: true,
        })
    )
}

const createCase = async (
    req: IncomingMessage,
    res: ServerResponse<IncomingMessage>
) => {
    res.setHeader('Content-Type', 'application/json')
    const params = urlParamsToObj(req.url || '')
    const { caseKey } = params

    if (!caseKey) {
        res.end(
            JSON.stringify({
                success: false,
                data: 'caseKey is required',
            })
        )
        return
    }

    const teachCaseDir = path.resolve('./src/teaching-cases')
    const templateDir = path.resolve(teachCaseDir, '_template')
    const newCaseDir = path.resolve(teachCaseDir, caseKey)
    const caseListTsFile = path.resolve('./src/pages/CaseList/caseList.ts')

    // 复制模板到新文件夹
    fs.cpSync(templateDir, newCaseDir, { recursive: true })

    // 修改caseList.ts
    const caseListTsFileContent = fs.readFileSync(caseListTsFile, 'utf-8')

    const newContent = caseListTsFileContent.replace(
        '// NEW_CASE',
        `{
        title: '新案例',
        key: '${caseKey}',
        // poster: bubbleSortPost,
    },
    // NEW_CASE
    `
    )

    fs.writeFileSync(caseListTsFile, newContent)

    console.log(req)
    res.end(
        JSON.stringify({
            success: true,
            data: true,
        })
    )
}

export const proxyReqListener = (
    _proxyReq: ClientRequest,
    req: IncomingMessage,
    res: ServerResponse<IncomingMessage>
) => {
    const url = req.url
    console.log(url)
    const handlerMap = {
        '/localhost-devServer/boardSave': boardSave,
        '/localhost-devServer/isDevlopment': isDevlopment,
        '/localhost-devServer/createCase': createCase,
    }

    const key = Object.keys(handlerMap).find((v) => url?.startsWith(v)) as
        | keyof typeof handlerMap
        | undefined

    if (key && handlerMap[key]) {
        handlerMap[key](req, res)
    }
}
